'use strict';
const {
  Model
} = require('sequelize');
var moment = require('moment')
moment.locale('zh-cn'); 
module.exports = (sequelize, DataTypes) => {
  class Chapter extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
        // define association here
        models.Chapter.belongsTo(models.Course, {as: 'course'})
    }
  }
  Chapter.init({
    courseId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
            notNull: {msg: '课程ID必须填写'},
            notEmpty: {msg: '课程ID不能为空'},
            async isPresent(value){
                const course = await Category.findOne({ where: { name: value } })
                if(!course){
                    throw new Error(`ID为: ${value} 的课程不存在`)
                }
            }
        }
    },
    title:{
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
            notNull: {msg: '标题必须填写'},
            notEmpty: {msg: '标题不能为空'},
            len: {args: [2, 35], msg: '长度需要在 2 ~ 35 个字符之间。'},
        }
    },
    content: DataTypes.TEXT,
    video:{
        type: DataTypes.STRING,
        validate: {
            isUrl: {msg: '视频地址不正确'},
        }
    },
    rank: DataTypes.INTEGER,
    createdAt: {
        type: DataTypes.DATE,
        get() {
            return moment(this.getDataValue("createdAt")).format("YYYY-MM-DD  hh:mm:ss")
        }
    },
    updatedAt: {
        type: DataTypes.DATE,
        get() {
            return moment(this.getDataValue("updatedAt")).format("YYYY-MM-DD  hh:mm:ss")
        }
    }
  }, {
    sequelize,
    modelName: 'Chapter',
  });
  return Chapter;
};